package com.njmaomao.gj.pyot.common;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Dom4JDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @since V1.0
 */
public class XmlUtil {

    private static final Logger log = LogManager.getLogger(XmlUtil.class);

    public static <T> T xml2Bean(String input, Class<T> clazz) {
        XStream xstream = new XStream(new Dom4JDriver());//更换为Dom4JDriver，防止xxe，可参考http://x-stream.github.io/faq.html#Security_XXEVulnerability
        xstream.setClassLoader(XmlUtil.class.getClassLoader());
        XStream.setupDefaultSecurity(xstream);
        xstream.addPermission(AnyTypePermission.ANY);
        xstream.processAnnotations(clazz);
        xstream.ignoreUnknownElements();//忽略未知xml节点

        return (T) xstream.fromXML(input);
    }

    public static Map<String, String> xmltoMap(String xml) {
        Map<String, String> map = new HashMap<>();
        try {
            Document document = DocumentHelper.parseText(xml);
            Element nodeElement = document.getRootElement();
            List node = nodeElement.elements();
            for (Iterator it = node.iterator(); it.hasNext(); ) {
                Element elm = (Element) it.next();
                map.put(elm.getName(), elm.getText());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return map;
    }

    public static String objectToXml(Object obj) {
        try {
            XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("-_", "_")));
            xStream.processAnnotations(obj.getClass());
            return xStream.toXML(obj);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

}
